package org.numb.concurrency.chapter03;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockDemo {

    private static int num;

    public static void main(String[] args) {
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        Thread t1 = new Thread(() -> {
            while (true) {
                lock.readLock().lock();
                if (num % 2 == 1) {
                    try {
                        TimeUnit.MICROSECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("thread 1, num = " + num);
                }
                lock.readLock().unlock();
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                lock.writeLock().lock();
                try {
                    TimeUnit.MICROSECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                num++;
                lock.writeLock().unlock();
            }
        });
        t1.start();
        t2.start();
    }
}
